import json
import datetime
class Project:
    def __init__(self):
        self.total = 0
        self.versions = "0"
        self.statuses = "0"
        self.updated = None
        
    def __str__(self):
        return "{}:{} {} {}".format(self.id,self.key,self.name,self.total)

    @staticmethod
    def fromJson(data):
        ret = Project()
        ret.name = data["name"]
        ret.id = data["id"]
        ret.key = data["key"]
        if "updated" in data:
            ret.updated = data["updated"]
        if "total" in data:
            ret.total = data["total"]
        return ret

    @staticmethod
    def from_file(file):
        print("process {}".format(file))
        data = json.load(open(file, encoding='utf8'))
        return Project(data)

class Issue:
    def __init__(self,data):
        self.id = data["key"]
        self.key = data["key"]
        self.issuetype = data["fields"]["issuetype"]["name"]
        self.summary = data["fields"]["summary"]
        self.status = None
        if "status" in data["fields"]:
            self.status = data["fields"]["status"]["name"].upper()
        self.sprint = None
        if "sprint" in data["fields"]:
            self.sprint = data["fields"]["sprint"]["name"]

        self.created_at = datetime.datetime.strptime(
                         data["fields"]["created"][:19], "%Y-%m-%dT%H:%M:%S")
        self.updated_at = datetime.datetime.strptime(
                         data["fields"]["updated"][:19], "%Y-%m-%dT%H:%M:%S")  # 2017-06-07T07:39:02.387+0800)
        self.creator = data["fields"]["creator"]["emailAddress"]

        # self.estimated = None
        # if mapping.get("estimated", None) and mapping["estimated"] in data["fields"]:
        # estimated = data["fields"][mapping["estimated"]]


        self.change_logs = []
        for i in data["changelog"]["histories"]:
            self.change_logs.append(ChangeLog(i,self))

    @staticmethod
    def from_file(file):
        print("process {}".format(file))
        data = json.load(open(file, encoding='utf8'))
        return Issue(data)

class ChangeLog:
    def __init__(self,data,issue):
        self.issue = issue
        self.id = data["id"]
        self.created = data["created"]
        self.author = data["author"]["emailAddress"]
        self.items = ",".join(list(map(lambda x:x["field"],data["items"])))

